{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fWHq8BOKVWkF"
      },
      "source": [
        "Copyright 2022 Google LLC\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "    https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v9t8O2rZVnB3"
      },
      "source": [
        "# Visualize models training/validation loss"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dAPgza3lUxqI"
      },
      "source": [
        "## Prepare colab"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lgfyIWNA_4ZR"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"  # no need to use gpu"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bqcuWa6aUz9G"
      },
      "outputs": [],
      "source": [
        "# bazel build -c opt --copt=-mavx2 //kws_streaming/colab:colab_notebook.par\n",
        "# ./bazel-bin/kws_streaming/colab/colab_notebook.par"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_AYtMz4zU20-"
      },
      "source": [
        "## Imports"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KdA3gfcAZVVB"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import os\n",
        "import numpy as np\n",
        "import math\n",
        "import os.path\n",
        "import sys\n",
        "import matplotlib.pyplot as plt"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Qw4JpQIp_4ZV"
      },
      "outputs": [],
      "source": [
        "tf = tf.compat.v1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z64Kkz7BU4l9"
      },
      "source": [
        "## Utils"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Gn2sW-d_EGlr"
      },
      "outputs": [],
      "source": [
        "def read_log(fname, tag=\"accuracy\"):\n",
        "  eval_acc = []\n",
        "  eval_loss = []\n",
        "  try:\n",
        "    for event in tf.train.summary_iterator(fname):\n",
        "      for value in event.summary.value:\n",
        "        if value.tag == tag:\n",
        "          eval_acc.append(value.simple_value)\n",
        "  except:\n",
        "    print(\"stop parsing \" + fname)\n",
        "\n",
        "  return eval_acc, eval_loss"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VjpDezzPEsDE"
      },
      "outputs": [],
      "source": [
        "def scan_log(log_path):\n",
        "  acc = []\n",
        "  found = False\n",
        "  if os.path.isdir(log_path):\n",
        "    for file in os.listdir(log_path):\n",
        "      if file.endswith(\".gtc\"):\n",
        "        validation_file = os.path.join(log_path, file)\n",
        "        acc = []\n",
        "        if os.path.isfile(validation_file):\n",
        "          if found:\n",
        "            raise ValueError(\"found duplicate log\")\n",
        "          acc, _ = read_log(validation_file)\n",
        "          found = True\n",
        "  return acc"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "57a3bxR_IW-T"
      },
      "outputs": [],
      "source": [
        "def train_eval_log(model_path):\n",
        "  log_path_train = os.path.join(model_path, \"logs\", \"train\")\n",
        "  acc_train = scan_log(log_path_train)\n",
        "  log_path_val = os.path.join(model_path, \"logs\", \"validation\")\n",
        "  acc_val = scan_log(log_path_val)\n",
        "  return acc_train, acc_val"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UJznYas_VBXv"
      },
      "source": [
        "## Read logs"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-YRaEmDaHDGd"
      },
      "outputs": [],
      "source": [
        "# set path to trained models\n",
        "model_path1 = \"/tmp/kws_streaming/models2/att_mh_rnn/\"\n",
        "model_path2 = \"/tmp/kws_streaming/models2/tc_resnet/\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vhPvo2loICdA"
      },
      "outputs": [],
      "source": [
        "acc_train1, acc_val1 = train_eval_log(model_path1)\n",
        "acc_train2, acc_val2 = train_eval_log(model_path2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "t6ls7mwVVENy"
      },
      "source": [
        "## Plot logs and compare models training/validation loss"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "T5UIZGZhI1UP"
      },
      "outputs": [],
      "source": [
        "# smoothing filter\n",
        "window = np.hanning(70)\n",
        "window = window/window.sum()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I6B7iYElI1SP"
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(20, 10))\n",
        "\n",
        "data_val1 = np.convolve(window, acc_val1, mode='valid')\n",
        "data_tr1 = np.convolve(window, acc_train1, mode='valid')\n",
        "\n",
        "data_val2 = np.convolve(window, acc_val2, mode='valid')\n",
        "data_tr2 = np.convolve(window, acc_train2, mode='valid')\n",
        "\n",
        "ratio1 = (float)(len(data_tr1)) / len(data_val1)\n",
        "ratio2 = (float)(len(data_tr2)) / len(data_val2)\n",
        "\n",
        "xx1 = ratio1 * np.arange(len(data_val1))\n",
        "plt_val1, = plt.plot(xx1, data_val1, label='val1')\n",
        "plt_train1, = plt.plot(data_tr1, label='train1')\n",
        "\n",
        "xx2 = ratio2 * np.arange(len(data_val2))\n",
        "plt_val2, = plt.plot(xx2, data_val2, label='val2')\n",
        "plt_train2, = plt.plot(data_tr2, label='train2')\n",
        "plt.ylim(0.6, 1.0)\n",
        "plt.legend(handles=[plt_val1, plt_train1, plt_val2, plt_train2])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2oKWs3Mw_4Zb",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(20, 10))\n",
        "plt_val1, = plt.plot(xx1, data_val1, label='val1')\n",
        "\n",
        "plt_val2, = plt.plot(xx2, data_val2, label='val2')\n",
        "plt.ylim(0.90, 1.0)\n",
        "plt.legend(handles=[plt_val1, plt_val2])\n",
        "plt.show()"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "last_runtime": {
        "build_target": "",
        "kind": "local"
      },
      "name": "visualize training, validation loss.ipynb",
      "provenance": [
        {
          "file_id": "1wP2hPrVOqiB8emOUADZRklHRZJFkC7Cl",
          "timestamp": 1579917787205
        },
        {
          "file_id": "1fBEsHtE-jTFofqtJYowI-vDSMokiy2mY",
          "timestamp": 1573319994394
        }
      ]
    },
    "kernelspec": {
      "display_name": "Python 2",
      "language": "python",
      "name": "python2"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 2
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython2",
      "version": "2.7.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
